//
//  MyViewController.m
//  FlowerRainGround
//
//  Created by lanou on 16/4/19.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "MyViewController.h"
#import "LoginViewController.h"
#import "UserSetViewController.h"
#import "UserCollectionModel.h"
#import "MyTableViewCell.h"
#import "HeadView.h"//图片拉伸的头视图
#import "UIHeadtableVIew.h"
#import "InfoViewController.h"
#import "LORefresh.h"
#define kItemWidth (kWidth - 25) / 2
@interface MyViewController ()<UITableViewDataSource , UITableViewDelegate>

@property (nonatomic, strong) UITableView *tabVC;
@property (nonatomic, strong) NSMutableArray *collectionModelArray;
@property (nonatomic, strong) HeadView *headView;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIView *sectionView;
@property (nonatomic, strong) UIHeadtableVIew *headTableView;
@property (nonatomic, assign) NSInteger starPage;
@property (nonatomic, assign) NSInteger limitPage;
@end

@implementation MyViewController

- (NSMutableArray *)collectionModelArray{
    if (_collectionModelArray == nil) {
        _collectionModelArray = [[NSMutableArray alloc] initWithCapacity:0];
        
    }
    return _collectionModelArray;
}

//请求数据
- (void) requestData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:[NSString stringWithFormat:@"http://m.htxq.net/servlet/UserCenterServlet?action=getMySubscibeContents&currentPageIndex=%ld&pageSize=%ld&userId=%@&(null)=",self.starPage,self.limitPage,[userManager getUsrID]] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSArray *array = dic[@"result"];
        for (NSDictionary *dic1 in array) {
            UserCollectionModel *model = [[UserCollectionModel alloc] init];
            [model setValuesForKeysWithDictionary:dic1];
            [self.collectionModelArray addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tabVC reloadData];
            //结束刷新
            [self.tabVC.defaultFooter endRefreshing];
            
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}




//当视图出现时如果没有得到用户的ID,就直接跳到登陆界面
- (void)viewWillAppear:(BOOL)animated{
    
    if ([[userManager getUsrID] isEqualToString:@" "]) {
        
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        [self presentViewController:loginVC animated:YES completion:nil];
     
    }else{
            [self.tabVC reloadData];
            [self requestData];
    }
}




//添加导航栏按钮
- (void)addNavigationBarItem{
    self.navigationItem.title = @"个人中心";
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"chilun"] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 25, 25);
    button.block = ^(){
        [self popToSetUserInformationView];
    };
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = right;
}

//跳转到设置界面
- (void)popToSetUserInformationView
{
    UserSetViewController *userVC = [[UserSetViewController alloc] init];
    [self.navigationController pushViewController:userVC animated:YES];
}


#pragma mark---------创建头视图  及tableView-------
//设置creatTableVC;
- (void) creatTableVC
{
    self.tabVC = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    self.tabVC.delegate = self;
    self.tabVC.dataSource = self;
    self.tabVC.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tabVC];
    
    //上拉刷新
    __weak MyViewController *myself = self;
    [self.tabVC addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        _starPage = 0;
        _limitPage += 10;
        [myself requestData];
    }];
    
    
    
    
    //拉伸视图,uimageView
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 200)];
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    self.imageView.clipsToBounds = YES;
    self.imageView.image = [UIImage imageNamed:@"flower"];
    
    
 
    //用户的头视图View;
    _headTableView = [[UIHeadtableVIew alloc] initWithFrame:self.imageView.bounds];
    _headTableView.backgroundColor = [UIColor clearColor];
    //打开头像的交互
    _headTableView.headImageView.userInteractionEnabled = YES;
    //给头像添加点击事件
    UITapGestureRecognizer *tapHeadImage = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHeadImage)];
    [_headTableView.headImageView addGestureRecognizer:tapHeadImage];
  
    
    self.headView = [HeadView new];
    [self.headView stretchHeaderForTableView:self.tabVC withView:self.imageView subView:_headTableView];
    

    //注册cell
    [self.tabVC registerNib:[UINib nibWithNibName:@"MyTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"reuse"];
    
}

//轻拍头像触发的方法
- (void) tapHeadImage
{

    [HeadImageSizeView showImage:_headTableView.headImageView];
}







- (void)viewDidLoad {
    [super viewDidLoad];
    self.starPage = 0;
    self.limitPage = 10;
   
    self.navigationController.navigationBar.translucent = NO;

    [self creatTableVC];
    [self addNavigationBarItem];
    
    
    
    
    
    
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // Do any additional setup after loading the view from its nib.
}


#pragma mark--------tableVCdateDelegate-------

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.collectionModelArray.count;
    
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 240;
}

//创建cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *reuse = @"reuse";
    UserCollectionModel *model = self.collectionModelArray[indexPath.row];
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse forIndexPath:indexPath];
    if (!cell) {
        cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
   //给cell赋值
    cell.watchLabel.text = [NSString stringWithFormat:@"%@",model.read] ;
    cell.collectlabel.text = [NSString stringWithFormat:@"%@", model.appoint];
    cell.introducelabel.text = model.desc;
    cell.titleLabel.text = model.title;
    [cell.headImageVIew sd_setImageWithURL:[NSURL URLWithString:model.smallIcon]];

    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}

//设置分区头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    switch (section) {
        case 0:{
            //现在分区头放一个view
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 50)];
            //view上放一个label
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(-1, 0, kWidth +1, 49)];
            label.text = @"订阅";
            label.backgroundColor = [UIColor whiteColor];
            label.textAlignment = 1;
            //view最小面放一条黑线
            UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 49, kWidth, 1)];
            view1.backgroundColor = [UIColor blackColor];
            [view addSubview:view1];
            [view addSubview:label];

            return view;

            break;}
        default:
            break;
    }
   
    return nil;
    
}

//选中行
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UserCollectionModel *model = self.collectionModelArray[indexPath.row];
    InfoViewController *infoVC = [[InfoViewController alloc] init];
    infoVC.ContantId = model.ID;//传id
    infoVC.stringTitle = model.title;//传标题
    [self.navigationController pushViewController:infoVC animated:YES];
}





#pragma mark -----图片的拉伸-----


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.headView scrollViewDidScroll:scrollView];
}


- (void)viewDidLayoutSubviews{
    [self.headView resizeView];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
